package com.smp.filter;

import com.smp.annotation.Authorization;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author: fangxiaoyu
 * @date: 2021/6/30
 * @description:
 **/
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 处理token验证
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        // 获取方法上的Authorization注解
        Authorization authAnnotation = this.getMethodAuthAnnotation(handlerMethod.getMethod());
        if (authAnnotation != null && authAnnotation.value().equals(Authorization.AuthCode.ALLOW)) {
            return true;
        }
        log.error(" =============== 没有权限 ===============");
        // 从表头获取信息 || 从URL后面的参数获取信息
        // String token = request.getHeader(TOKEN_KEY);
        // Map<String, String[]> params = request.getParameterMap();
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 放行的接口如果使用MDC，则自己清除
        log.info("清除MDC的值");
        MDC.clear();
    }

    private Authorization getMethodAuthAnnotation(Method method) {
        Authorization annotation = method.getAnnotation(Authorization.class);
        return annotation;
    }

}
